package org.linlinjava.litemall.db.service;

import java.text.MessageFormat;

import javax.annotation.Resource;

import org.linlinjava.litemall.db.dao.LitemallSequenceMapper;
import org.linlinjava.litemall.db.domain.LitemallSequence;
import org.linlinjava.litemall.db.domain.LitemallSequenceExample;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;

/**
 * 序列管理
 * 
 * @author geshichun
 *
 */
@Service
public class LitemallSequenceService {
	@Resource
	private LitemallSequenceMapper SequenceMapper;

	private static String getNumStr(int num) {
		return getNumStr(num, 0L);
	}

	private static String getNumStr(int num, Long value) {
		return String.format(new StringBuffer("%0").append(num).append("d").toString(), value);
	}

	@Transactional(rollbackFor = Exception.class)
	private LitemallSequence getLitemallSequence(Integer num, String sequenceType, String identify) {
		String syncStr = MessageFormat.format("{0}", sequenceType).intern();
		synchronized (syncStr) {
			LitemallSequenceExample example = new LitemallSequenceExample();
			LitemallSequenceExample.Criteria criteria = example.createCriteria();
			criteria.andSequenceTypeEqualTo(sequenceType);

			LitemallSequence sequence = SequenceMapper.selectOneByExample(example);
			if (sequence == null) {
				sequence = new LitemallSequence();
				sequence.setSequenceName(sequenceType);
				sequence.setSequenceType(sequenceType);
				sequence.setSequenceValue(getNumStr(num));
				sequence.setIdentify(identify);
				SequenceMapper.insert(sequence);
			}
			// 标识（目前支持日期标识）不等的情况下，更新标识，并重置序列
			if (!StringUtils.equals(sequence.getIdentify(), identify)) {
				sequence.setSequenceValue(getNumStr(num));
				sequence.setIdentify(identify);
			}
			sequence.setSequenceValue(getNumStr(num, Long.parseLong(sequence.getSequenceValue()) + 1));
			SequenceMapper.updateByPrimaryKey(sequence);
			return sequence;
		}
	}

	public String getNextValue(Integer num, String sequenceType, String identify) {
		if (num == null) {
			num = 5;
		}
		LitemallSequence entity = getLitemallSequence(num, sequenceType, identify);
		if (entity == null) {
			throw null;
		}
		return String.valueOf(entity.getSequenceValue());
	}

}
